package com.example.demo.handler;

import com.example.demo.custom.CustomResponse;
import com.example.demo.exception.JwtValidationException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(JwtValidationException.class)
    public CustomResponse<String> handleJwtValidationException(JwtValidationException e) {
        CustomResponse<String> result = new CustomResponse<>(401, e.getMessage(), null);
        return result;
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public CustomResponse<String> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        List<ObjectError> allErrors = e.getAllErrors();
        StringBuilder errorMessage = new StringBuilder();
        for (ObjectError allError : allErrors) {
            String defaultMessage = allError.getDefaultMessage();
            errorMessage.append(defaultMessage).append(",");
        }
        CustomResponse<String> result = new CustomResponse<>(400, errorMessage.toString(), null);
        return result;
    }
}